import axios from "axios";
import { getToken } from '@/utils/auth'
import store from '@/store'
import { MessageBox, Message } from 'element-ui'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000
})

// 配置请求拦截器
service.interceptors.request.use(
    config => {    
        if (store.getters.token) {
            // config.data = JSON.stringify(config.data)
            config.headers['token'] = getToken()
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
    
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        // debugger
        const res = response.data

        if (res.code !== 200) {
            Message({
                message: res.message || 'error',
                type: 'error',
                duration: 5*1000
            })
        }
        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else {
        return res
      }

    },
    error => {
        console.log('err' + error)
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
          })
          return Promise.reject(error)
    }
)

export default service